package com.jeff.client;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.telephony.PhoneNumberUtils;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.jeff.client.util.Constans;

public class EchoActivity extends Activity {
	Button button_getContact = null;
	Button button_query = null;
	TextView textView_info = null;
	TextView infoText2 = null;
	private EchoClient echoClient = null;
	private String phoneNum = null;
	private LocationManager lm = null;
	private Location location = null;
	private String localPhone = null;
	private String destPhone = null;

	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        login();
        
        init();
        
        button_query = (Button) findViewById(R.id.button_Query);
        button_query.setOnClickListener(new View.OnClickListener() {
        	@Override
        	public void onClick(View v) {
        		Log.i("yao", "clicked b2");
        		test();
        		TextView textViewPhone = (TextView)findViewById(R.id.textView_Phone);
        		String destPhone = textViewPhone.getText().toString();
        		TextView textViewQueryResult = (TextView)findViewById(R.id.textView_queryResult);	
        		if(destPhone==null || destPhone.length()==0 || !PhoneNumberUtils.isGlobalPhoneNumber(destPhone)) {
        			Toast.makeText(getApplicationContext(), 
				              "not a valid number, please have a check", 
				              Toast.LENGTH_LONG).show(); 
        			return;
        		}
        		String locationInfo = getLocation();
        		String localPhone = getLocalPhone();
        		if(localPhone == null || localPhone.length()==0) {
        			Toast.makeText(getApplicationContext(), 
				              "can't get the local phone number", 
				              Toast.LENGTH_LONG).show(); 
        			return ;
        		}
        		if(locationInfo == null) {
        			Toast.makeText(getApplicationContext(), 
        					"can't get the location, please check enable locate service", 
        					Toast.LENGTH_LONG).show(); 
        		}

        		StringBuilder sb = new StringBuilder();
        		sb.append(destPhone).append("\t").append(localPhone);
        		if(locationInfo != null) {
        			sb.append("\t").append(locationInfo);
        		}
        		echoClient.sendMsg(sb.toString());
        		String recvMsg = echoClient.receiveMsg();
        		textViewQueryResult.setText(recvMsg);
        	}
        });

        button_getContact = (Button) findViewById(R.id.button_getPhone);
        button_getContact.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Log.i("yao", "clicked b2");
				chooseContact();
			}
		});

    }
    
    
    private String getLocation() {
    	if(location != null) {
    		return location.getLongitude() + ":" + location.getLatitude();
    	}
    	return null;
    }
    
    private void chooseContact() {
    	Intent i = new Intent(this, ChooseContact.class); 
        startActivity(i);
    }
    
    private boolean init() {
    	textView_info = (TextView)findViewById(R.id.textView_info);	
    	//init network
    	echoClient = new EchoClient(Constans.LISTEN_DATA_IP, Constans.LISTEN_DATA_PORT);
    	
    	LocationManager lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(true);
        criteria.setBearingRequired(true);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);
        String bestProvider = lm.getBestProvider(criteria, true);
        Log.i("yao", "bestProvider = " + bestProvider);
        textView_info.setText("get location from " + bestProvider);
        
        LocationListener locationListener = new LocationListener() {
        	@Override
			public void onLocationChanged(Location location) {
				Log.i("yao", location.toString());
				EchoActivity.this.location = location;
			}

        	@Override
			public void onProviderDisabled(String arg0) {
				Log.i("yao", arg0);
			}

        	@Override
			public void onProviderEnabled(String arg0) {
				Log.i("yao", arg0);
			}

        	@Override
			public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
				Log.i("yao", "onStatusChanged");
			}
        };
        sleep(5000);
        lm.requestLocationUpdates(bestProvider, 1000, 0, locationListener);
    	
    	TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); 
        String deviceid = tm.getDeviceId(); 
        String tel = tm.getLine1Number(); 
        String  imei = tm.getSimSerialNumber();       
        String imsi = tm.getSubscriberId();
        phoneNum = deviceid + "," + tel + ","+ imei + "," + imsi;
    	return true;
    }
    
    private String getLocalPhone() {
    	TelephonyManager tm = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); 
    	String deviceid = tm.getDeviceId(); 
        String phone = tm.getLine1Number(); 
        String  imei = tm.getSimSerialNumber();       
        String imsi = tm.getSubscriberId();
        if(phone == null || phone.length() == 0) {
        	try {
				BufferedReader br = new BufferedReader(new FileReader(Constans.PERSIST_FILE));
				String line = br.readLine();
				if(line == null) {
					return null;
				}else {
					phone = line.split("\t")[0];
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
    	return phone;
    }
    
    private boolean register() {
    	return true;
    }
    
    private void login() {
    	Intent intent = new Intent(this, Login.class); 
        startActivity(intent);
    }
    
    private void sleep(long millsecs) {
    	try {
			Log.i("yao", "sleeping " + millsecs);
			Thread.sleep(millsecs);
		}catch(Exception e) {
			
		}
    }
    
    private void test() {
    }
}